import hh.util.Recorder;
import hh.util.jdbc.JdbcUtil;

import java.sql.Connection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MysqlDeadLock {

    static Recorder recorder = new Recorder(500);

    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
        String sql = "UPDATE `test`.`user` SET `name` = 'hh', `age` = 18, `addr` = 'bbb' WHERE `id` = 1";


        int poolSize = 30;
        ExecutorService pool = Executors.newFixedThreadPool(poolSize);
        for (int i = 0; i < poolSize; i++) {
            pool.execute(() -> update(JdbcUtil.getConnection(url, "root", "root"), sql));
        }


    }

    private static void update(Connection connection, String sql) {

        try {
            connection.setAutoCommit(false);
            while (true) {
                JdbcUtil.update(connection, sql);
                recorder.record(1);
                Thread.sleep(5);
                connection.commit();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
